package com.ruoyi.ems.orderTimedTasks;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.ems.controller.OrderController;
import com.ruoyi.ems.controller.StaffController;
import com.ruoyi.ems.domain.Order;
import com.ruoyi.ems.domain.Product;
import com.ruoyi.ems.domain.RefundOrder;
import com.ruoyi.ems.domain.Staff;
import com.ruoyi.ems.service.IOrderService;
import com.ruoyi.ems.service.IProductService;
import com.ruoyi.ems.service.IRefundOrderService;
import com.ruoyi.ems.service.IStaffService;
import com.ruoyi.ems.utils.HttpTool;
import com.ruoyi.ems.utils.SignatureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component("OrderTimedTasks")
public class OrderTimedTasks {

    @Autowired
    private IRefundOrderService refundOrderService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    private StaffController staffController;

    @Autowired
    private OrderController orderController;

    @Autowired
    private IProductService productService;

//    private static String url ="http://127.0.0.1:8085/api/t-order";
    private static String url ="http://47.110.49.47:8085/api/t-order";
    // 积分回退
    @Transactional
    public void refundPoints(){
        // 扫表，查到所有退款中的退款单
        List<RefundOrder> refundOrderList = refundOrderService.selectRefundOrderByStates("PROCESSING");
        for (RefundOrder refundOrder : refundOrderList) {

            String tradeNo = refundOrder.getTradeNo();
            Order order = orderService.selectOrderByCode(tradeNo);
            if (order == null){
                log.error("回退积分异常，订单号：{}", tradeNo);
                continue;
            }
            Long openId = order.getOpenId();


            if (!Objects.equals(refundOrder.getRefundAmount(), order.getTotalPrice())){
                log.error("订单积分与退款单积分不一致，请及时查看，订单积分：{}，退款单积分：{}", order.getTotalPrice(), refundOrder.getRefundAmount());
                refundOrder.setUpdateTime(new Date());
                refundOrder.setStatus("ABNORMAL");
            } else {
                Staff staff = staffService.selectStaffById(openId);
                // 积分
                RefundOrder refundOrderTmp = refundOrderService.selectRefundOrderById(refundOrder.getId());
                if ("SUCCESS".equals(refundOrderTmp.getStatus())){
                    continue;
                }
                Integer totalPrice = order.getTotalPrice();
                // 将当前订单积分加上
                staff.setScoreTmp(totalPrice);
                staff.setScoreExplainInfo("订单积分回退，订单号：" + order.getOrderCode());
                log.info("订单积分回退，订单号：{}，退回人：{}", order.getOrderCode(), staff.getName());
                // 更新员工的积分
                staffController.updateStaffScore(staff);
                refundOrder.setSuccessTime(new Date());
                refundOrder.setStatus("SUCCESS");
                // 卡劵更新库存
                if (order.getType().equals("coupons")){
                    String productCode = order.getProductCode();
                    Product product = productService.selectProductByCode(productCode);
                    product.setStock(product.getStock() + 1L);
                    productService.updateProduct(product);
                }
            }
            refundOrderService.updateRefundOrder(refundOrder);
        }
    }

    // 查询卡劵订单状态，定时扫描
    @Transactional
    public void queryOrderStatus(){
        long timeNow = System.currentTimeMillis();
        // 查询除了成功和失败的订单
        List<Order> orderList = orderService.selectOrderListByStatus("coupons");
        String urlIp = "http://120.26.223.111:9090/v1/QueryOrder";

        for (Order order : orderList) {
            HashMap<String, String> params = new HashMap<>();
            params.put("Service","QueryOrder");
            params.put("UserId", "test"); //账号配置 test
            params.put("BizType","ECARD");  //类型要换
            params.put("OrderNo", order.getOrderCode()); //订单号
            params.put("Time",String.valueOf(timeNow));//时间戳
            String sign = SignatureUtil.generateSign(params, "a367b552cfe347cc88e883158c0f7482"); // 暂无apiKey
            params.put("Sign",sign);//签名

            String res = HttpTool.sendPost33(urlIp, params);
            //拿到响应数据
            JSONObject objectRes = JSONObject.parseObject(res);
            String code = String.valueOf(objectRes.getString("code"));
            String msg = objectRes.getString("msg");
            String orderStatus = objectRes.getString("OrderStatus");
            // 0 查询成功，修改订单状态
            if ("0".equals(code)){
                // 响应成功
                if ("FAILED".equals(order.getOrderStatus()) || "SUCCESS".equals(order.getOrderStatus())){
                    continue;
                }
                String productData = objectRes.getString("ProductData");
                // 订单失败，创建退款单,订单状态失败或者订单不存在，都设置成失败
                if ("FAILED".equals(orderStatus) || "NOTEXIST".equals(orderStatus)){
                    orderController.creatRefundOrder(order);
                    order.setOrderStatus("FAILED");
                } else {
                    // 其余状态都设置上
                    order.setOrderStatus(orderStatus);
                }
                order.setOrderInfo(productData);
                order.setChangeTime(new Date());
                order.setErrMsg(msg);
                orderService.updateOrder(order);
            } else {
                // 查询失败
                log.info("查询订单状态接口失败，提单返回状态："+code+msg);
            }
        }
    }

    // 查询okr订单状态，定时扫描
    @Transactional
    public void queryOrderStatusLocalLife(){
        // 查询除了成功和失败的订单
        List<Order> orderList = orderService.selectOrderListByStatus("goods");
        String urlIp = url +"/okrQueryOrderStatus";

        for (Order order : orderList) {
            String orderNumber = order.getUpstreamOrderNumber();
            String res = HttpTool.sendPostStr(urlIp, orderNumber);
            //拿到响应数据
            JSONObject objectRes = JSONObject.parseObject(res);
            String code = String.valueOf(objectRes.getString("code"));
            String msg = objectRes.getString("message");
            JSONObject data = objectRes.getJSONObject("data");
            // 0 查询成功，修改订单状态
            if ("200".equals(code)){
                // 响应成功
                String orderStatus = data.getString("orderStatus");
                String orderInfo = data.getString("orderInfo");
                if (!"SUCCESS".equals(orderStatus) && !"FAILED".equals(orderStatus)){
                    log.info("okr查询订单状态接口，订单编号：{}，返回订单状态：{}", orderNumber,orderStatus);
                    order.setChangeTime(new Date());
                    orderService.updateOrder(order);
                    continue;
                }
                // 订单失败，创建退款单
                if ("FAILED".equals(orderStatus)){
                    orderController.creatRefundOrder(order);
                }
                order.setOrderStatus(orderStatus);
                order.setOrderInfo(orderInfo);
                order.setChangeTime(new Date());
                order.setErrMsg(msg);
                orderService.updateOrder(order);
            } else {
                // 查询失败
                log.info("查询订单状态接口失败，提单返回状态："+code+msg);
            }
        }
    }
}
